package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.util.UUIDUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/common")
public class CommonController {
    //读取配置文件中上文件的目录
    @Value("${reggie.path}")
    private String baseDir;

    //文件上传
    @PostMapping("/upload")
    public R<String> fileUpload(MultipartFile file) throws Exception {
        //获取文件名
        //有个问题,上传的文件名可能重复
        //所以需要重新给文件起名最大程度保证唯一性
        String fileName = file.getOriginalFilename();
        String fileExtName = fileName.substring(fileName.lastIndexOf("."));
        //创建唯一标识
        String fileNewName = UUIDUtils.getUUID() + fileExtName;
        //保存到指定磁盘下,判断指定磁盘是否有改文件名,没有就创建
        File dir = new File(baseDir);
        if (!dir.exists()) {
            dir.mkdirs();//没有就创建文件存储目录
        }
        //进行保存
        file.transferTo(new File(baseDir + fileNewName));
        //返回结果
        return R.success(fileNewName);
    }

    //文件下载
    @RequestMapping("/download")
    public void download(@RequestParam("name") String fileName, HttpServletResponse response) throws Exception {
        //输入流
        InputStream fileInputStream = new FileInputStream(baseDir + fileName);
        //输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //将输入流给输出流
        IOUtils.copy(fileInputStream, outputStream);
    }

}
